<?php
namespace app\tadmin\controller;
use app\common\model\AdsSite as AdsSiteModel;
use app\common\model\Ads as AdsModel;
use think\facade\Request;
/**
 * 广告管理
 */
class Manage extends Controller {
    /**
     * @param $sitep adsbw的parent_id
     * @param $sites adsbw的ID
     */
    public function index(){
        list($sitep , $sites , $siteList) = $this->initData();
        $where = ['a.adsbw_id' => $sites];
        if($sites <= 0){
            $adsbwIds = [];
            foreach($siteList as $v){
                $adsbwIds[] = $v['id'];
            }
            $where = ['a.adsbw_id' => $adsbwIds];
        }
        $list = AdsModel::field('a.*,b.bwtitle as site_name')
            ->alias('a')
            ->join('__ADSBW__ b' , 'b.id=a.adsbw_id')
            ->where($where)
            ->order('id desc')
            ->paginate(10);
        return $this->fetch('index' , compact('list' , 'sitep' , 'sites' , 'siteList'));
    }

    public function add(){
        if (!$this->request->isAjax()) {
            list($sitep , $sites , $siteList) = $this->initData();
            return $this->fetch('add', compact('sitep' , 'sites' , 'siteList'));
        }
        $model = new AdsModel;
        $data = $this->postData('ads');
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('manage/index',['sitep'=>$data['sitep'] , 'sites'=>$data['sites']]));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    public function edit(){
        if (!$this->request->isAjax()) {
            list($sitep , $sites , $siteList) = $this->initData();
            $ads = AdsModel::get(input('id'));
            $site = AdsSiteModel::get($ads->adsbw_id);
            return $this->fetch('edit', compact('site','ads' , 'sitep' , 'sites' , 'siteList'));
        }
        $data = $this->postData('ads');
        $model = AdsModel::get($data['id']);
        if ($model->edit($data)) {
            return $this->renderSuccess('编辑成功', url('manage/index',['sitep'=>$data['sitep'] , 'sites'=>$data['sites']]));
        }
        $error = $model->getError() ?: '编辑失败';
        return $this->renderError($error);
    }
    /**
     * 公共参数
     */
    private function initData(){
        $sitep = input('sitep' , 1);
        $sites = input('sites' , 0);
        $siteList = AdsSiteModel::where('parent_id' , $sitep)->select();//adsbw
        return [$sitep , $sites , $siteList];
    }

    public function delete($id){
        $model = AdsModel::get($id);
        if (!$model->delete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function change(){
        $ids = input('ids/a');
        $field = input('field');
        $value = input('value');
        if (AdsModel::where('id','in' , $ids)->update([$field=>$value]) > 0) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError('修改失败');
    }

}